using Microsoft.EntityFrameworkCore;
using net_work.Config;
using net_work.Data.DTO.Sys;
using net_work.Data.Entity.Sys;
using net_work.IRepository.Sys;

namespace net_work.Repository.Sys;

public class PersonRepository(ApplicationDbContext dbContext) : Repository<Person>(dbContext), IPersonRepository
{
    public async Task<long> InsertAsync(PersonAddRequest personAddRequest)
    {
        var existingPerson = await dbContext.People
            .IgnoreQueryFilters()
            .Where(p => p.PsnIdNum == personAddRequest.PsnIdNum)
            .FirstOrDefaultAsync();

        if (existingPerson != null)
        {
            return -1;
        }

        var newPerson = new Person
        {
            PsnName = personAddRequest.PsnName,
            PsnGen = personAddRequest.PsnGen,
            PsnIdType = personAddRequest.PsnIdType,
            PsnIdNum = personAddRequest.PsnIdNum,
            PsnBirDate = personAddRequest.PsnBirDate,
            PsnAddr = personAddRequest.PsnAddr,
            PsnBirAddr = personAddRequest.PsnBirAddr,
            PsnNat = personAddRequest.PsnNat,
            PsnRen = personAddRequest.PsnRen,
            Remark = personAddRequest.Remark
        };

        await dbContext.People.AddAsync(newPerson);
        await dbContext.SaveChangesAsync();
        return newPerson.Id;
    }

    public async Task<bool> UpdateAsync(PersonUpdateRequest personUpdateRequest)
    {
        var people = await dbContext.People
            .IgnoreQueryFilters()
            .Where(p => p.PsnIdNum == personUpdateRequest.PsnIdNum || p.Id == personUpdateRequest.Id)
            .ToListAsync();

        var conflictPerson = people.FirstOrDefault(p => p.Id != personUpdateRequest.Id);
        if (conflictPerson != null)
        {
            return false;
        }

        var existingPerson = people.FirstOrDefault(p => p.Id == personUpdateRequest.Id);
        if (existingPerson == null)
        {
            return false;
        }
        
        existingPerson.Remark = personUpdateRequest.Remark;
        existingPerson.PsnName = personUpdateRequest.PsnName;
        existingPerson.PsnGen = personUpdateRequest.PsnGen;
        existingPerson.PsnIdType = personUpdateRequest.PsnIdType;
        existingPerson.PsnIdNum = personUpdateRequest.PsnIdNum;
        existingPerson.PsnBirDate = personUpdateRequest.PsnBirDate;
        existingPerson.PsnAddr = personUpdateRequest.PsnAddr;
        existingPerson.PsnBirAddr = personUpdateRequest.PsnBirAddr;
        existingPerson.PsnNat = personUpdateRequest.PsnNat;
        existingPerson.PsnRen = personUpdateRequest.PsnRen;

        await dbContext.SaveChangesAsync();
        return true;
    }
}